package com.bsj.travel.mqtt.configure;

import cn.hutool.core.net.NetUtil;
import com.bsj.travel.constants.RedisConstant;
import com.bsj.travel.util.ip.GetEth0IpUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.INetUtil;
import net.dreamlu.mica.redis.cache.MicaRedisCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @author yinhao
 * @version 1.0
 * @description redis监听
 * @date 2024/5/14
 */
@Configuration
@Slf4j
public class RedisMessageListener {

    @Bean
    public RedisMessageListenerContainer container(MicaRedisCache redisCache, MqttConnectRedisListener listener) {
        RedisConnectionFactory factory = redisCache.getRedisTemplate().getConnectionFactory();
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        //只订阅自己的消息
        String nodeName = GetEth0IpUtil.getHostAddress();
        String topicConnect = RedisConstant.LINE_PUB_SUB_TOPIC + nodeName;
        log.info("当前节点订阅到Connect redis主题： {}", topicConnect);
        container.addMessageListener(listener, new ChannelTopic(topicConnect));
        return container;
    }
}
